<template>
  <view class="nav-bar">
    <!-- 左侧区域 -->
    <view class="nav-left">
      <slot name="left">
        <BaseButton
          v-if="showBack"
          type="ghost"
          size="small"
          @click="handleBack"
        >
          <template #prefix>
            <text class="i-carbon-chevron-left"></text>
          </template>
          返回
        </BaseButton>
      </slot>
    </view>

    <!-- 中间标题区域 -->
    <view class="nav-center">
      <text class="nav-title">{{ title }}</text>
      <text v-if="subtitle" class="nav-subtitle">{{ subtitle }}</text>
    </view>

    <!-- 右侧区域 -->
    <view class="nav-right">
      <slot name="right">
        <view class="nav-actions">
          <BaseButton
            v-for="action in actions"
            :key="action.key"
            type="ghost"
            size="small"
            @click="action.handler"
          >
            <BaseIcon :name="action.icon" size="small" />
          </BaseButton>
        </view>
      </slot>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import BaseButton from '../ui/BaseButton.vue'
import BaseIcon from '../ui/BaseIcon.vue'

interface NavAction {
  key: string
  icon: string
  handler: () => void
}

interface Props {
  // 导航栏标题
  title?: string
  // 副标题
  subtitle?: string
  // 是否显示返回按钮
  showBack?: boolean
  // 是否固定在顶部
  fixed?: boolean
  // 背景样式
  background?: 'transparent' | 'solid' | 'blur'
  // 右侧操作按钮
  actions?: NavAction[]
  // 自定义类名
  customClass?: string
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  subtitle: '',
  showBack: false,
  fixed: true,
  background: 'solid',
  actions: () => [],
  customClass: '',
})

const emit = defineEmits<{
  back: []
}>()

// 导航栏样式
const navBarClass = computed(() => {
  const baseClass = 'nav-bar'

  const positionClass = props.fixed ? 'fixed top-0 left-0 right-0 z-40' : ''

  const backgroundClasses = {
    transparent: 'bg-transparent',
    solid: 'bg-bg-medium border-b border-custom',
    blur: 'bg-bg-medium/80 backdrop-blur-lg border-b border-custom/50',
  }

  return [
    baseClass,
    positionClass,
    backgroundClasses[props.background],
    props.customClass,
  ].filter(Boolean).join(' ')
})

// 处理返回
const handleBack = () => {
  emit('back')
  // 如果没有监听back事件，使用默认返回逻辑
  if (typeof uni !== 'undefined') {
    uni.navigateBack()
  }
}
</script>

<style scoped>
.nav-bar {
  @apply flex items-center justify-between px-md safe-area-top;
  height: 88rpx;
}

.nav-left {
  @apply flex items-center flex-1;
}

.nav-center {
  @apply flex flex-col items-center flex-1 text-center;
}

.nav-title {
  @apply text-base font-semibold text-text-primary;
}

.nav-subtitle {
  @apply text-xs text-text-secondary mt-1;
}

.nav-right {
  @apply flex items-center justify-end flex-1;
}

.nav-actions {
  @apply flex items-center gap-2;
}
</style>